package my.project.zuul.filter;

import com.netflix.zuul.ZuulFilter;
import com.netflix.zuul.context.RequestContext;
import org.apache.log4j.Logger;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

/**
 * Created by 哲 on 2016/11/29.
 */
public class AccessFilter extends ZuulFilter {

    private static final Logger logger = Logger.getLogger(AccessFilter.class);

    @Override
    public String filterType() {
        return "pre";
    }

    @Override
    public int filterOrder() {
        return 0;
    }

    @Override
    public boolean shouldFilter() {
        return true;
    }

    @Override
    public Object run() {
        RequestContext ctx = RequestContext.getCurrentContext();
        HttpServletRequest request = ctx.getRequest();
        logger.info(String.format("%s request to %s", request.getMethod(), request.getRequestURL().toString()));
        Object accessToken = request.getParameter("accessToken");
        if(accessToken == null) {
            logger.warn("access token is empty");
            ctx.setSendZuulResponse(false);
            ctx.setResponseStatusCode(401);
            return null;
        }
        /**
         * 服务是无状态的，因此session传入将改变值
         * 将session值保存至Cookie中
         * 或者在zuul的application.properties中配置zuul.sensitiveHeaders=
         */
        HttpSession session = request.getSession();
        ctx.addZuulRequestHeader("Cookie","SESSION="+session.getId());

        logger.info("access token ok");
        return null;
    }
}
